package com.op.teachingliteapp.fragment.smartpan;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.op.teachingliteapp.R;
import com.op.teachingliteapp.bean.FileBean;
import com.op.teachingliteapp.common.BaseApp;
import com.op.teachingliteapp.common.Common;
import com.op.teachingliteapp.common.api.ApiConstant;
import com.op.teachingliteapp.common.api.smartpan.CmdForm;
import com.op.teachingliteapp.common.api.smartpan.EntityBean;
import com.op.teachingliteapp.util.FileUtils;
import com.op.teachingliteapp.util.SharedPreferencesUtils;
import com.op.teachingliteapp.util.SmartPanUtils;
import com.op.teachingliteapp.util.StringUtils;
import com.op.teachingliteapp.util.ToastUtils;
import com.op.teachingliteapp.util.asynctask.HttpPostTask;
import com.op.teachingliteapp.util.asynctask.OnTaskProcessListener;

/**
 * Created by 陈宇瀚 on 2015/7/14.
 * 
 */
@SuppressLint({ "ResourceAsColor", "DefaultLocale", "InflateParams" })
public class SmartPanListviewAdapter extends BaseAdapter {
	private Context context;
	private List<FileBean> list;
	private String ownerId;
	private String folderPath;

	public SmartPanListviewAdapter(Context context, List<FileBean> list, String folderPath) {
		this.context = context;
		this.list = list;
		this.folderPath = folderPath;
	}

	public void setList(List<FileBean> list) {
		this.list = list;
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public String getFileSize(int position) {
		return list.get(position).getSize();
	}

	public String getFileName(int position) {
		return list.get(position).getName();
	}

	public boolean isFile(int position) {
		return list.get(position).isFile();
	}

	@SuppressLint("ResourceAsColor")
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ownerId = SharedPreferencesUtils.get(Common.Prefs.USER_ID, context);
		boolean isAllChoose = SharedPreferencesUtils.getInstance(BaseApp.getAppContext()).getBoolean(Common.Prefs.DROP_DOWN_BUTTON_CONDITION, false);
		final ViewHolder viewHolder;
		if (null == convertView) {
			viewHolder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(R.layout.item_smart_pan, null);
			viewHolder.mySmartPanFileChoose = (CheckBox) convertView.findViewById(R.id.smart_file_choose);
			viewHolder.mySmartPanFileName = (TextView) convertView.findViewById(R.id.smart_pan_item_file_name);
			viewHolder.mySmartPanFileDelete = (ImageButton) convertView.findViewById(R.id.smart_pan_item_file_delete);
			viewHolder.mySmartPanFileDown = (ImageButton) convertView.findViewById(R.id.smart_pan_item_file_down);
			viewHolder.mySmartPanFileType = (ImageView) convertView.findViewById(R.id.smart_pan_file_type);
			viewHolder.mySmartPanFileTime = (TextView) convertView.findViewById(R.id.smart_pan_item_file_time);
			viewHolder.mySmartPanFileSize = (TextView) convertView.findViewById(R.id.file_size);
			viewHolder.mySmartPanDownBar = (ProgressBar) convertView.findViewById(R.id.smart_pan_file_down_progressBar);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		// 判断是否全选
		viewHolder.mySmartPanFileChoose.setChecked(isAllChoose);
		String size = "";
		// 判断与云盘的文件是否对应，并设置相应控件显示
		if (list.get(position).getCondition().equals(Common.File.HAVA)) {
			viewHolder.mySmartPanFileName.setTextColor(Color.GRAY);
			viewHolder.mySmartPanFileDown.setVisibility(View.INVISIBLE);
			viewHolder.mySmartPanDownBar.setVisibility(View.INVISIBLE);
			if (list.get(position).isFile()) {
				viewHolder.mySmartPanFileDelete.setVisibility(View.VISIBLE);
				try {
					size = SmartPanUtils.convertFileSize(Long.parseLong(list.get(position).getSize()));
				} catch (Exception e) {
					size = list.get(position).getSize();
				}

			}
		} else if (list.get(position).getCondition().equals(Common.File.SMART_NO)) {
			viewHolder.mySmartPanFileName.setTextColor(Color.RED);
			viewHolder.mySmartPanFileDelete.setVisibility(View.VISIBLE);
			viewHolder.mySmartPanFileDown.setVisibility(View.INVISIBLE);
			viewHolder.mySmartPanDownBar.setVisibility(View.INVISIBLE);
			if (list.get(position).isFile()) {
				try {
					size = SmartPanUtils.convertFileSize(Long.parseLong(list.get(position).getSize()));
				} catch (Exception e) {
					size = list.get(position).getSize();
				}

			}
		} else if (list.get(position).getCondition().equals(Common.File.THIS_NO)) {
			viewHolder.mySmartPanFileName.setTextColor(Color.BLUE);
			viewHolder.mySmartPanFileDelete.setVisibility(View.INVISIBLE);
			viewHolder.mySmartPanDownBar.setVisibility(View.INVISIBLE);
			if (list.get(position).isFile()) {
				viewHolder.mySmartPanFileDown.setVisibility(View.VISIBLE);
				try {
					size = SmartPanUtils.convertFileSize(Long.parseLong(list.get(position).getSize()));
				} catch (Exception e) {
					size = list.get(position).getSize();
				}

			} else {
				viewHolder.mySmartPanFileDown.setVisibility(View.INVISIBLE);
			}
			// 判断是否正在下载
			if (list.get(position).getIsDown().equals(Common.File.DOWNLOAD)) {
				viewHolder.mySmartPanDownBar.setVisibility(View.VISIBLE);
				viewHolder.mySmartPanFileDown.setVisibility(View.INVISIBLE);
			} else {
				viewHolder.mySmartPanDownBar.setVisibility(View.INVISIBLE);
			}
		}
		viewHolder.mySmartPanFileSize.setText(size);
		
		if (list.get(position).getName().length() >= 15) {
			viewHolder.mySmartPanFileName.setText(list.get(position).getName().substring(0, 15));
		} else {
			viewHolder.mySmartPanFileName.setText(list.get(position).getName());
		}
		viewHolder.mySmartPanFileTime.setText(list.get(position).getUpdated());
		// 删除按钮监听
		viewHolder.mySmartPanFileDelete.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				final String fileName = list.get(position).getName();
				new AlertDialog.Builder(context).setTitle("提示").setMessage("确定删除该文件夹 : " + fileName).setNegativeButton("取消", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).setPositiveButton("确定", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						String path = list.get(position).getPath();
						path = path.substring(0, path.lastIndexOf("/")).replace(Common.rootFilePath.ROOT_FILE_PATH + ownerId, "");

						Log.i("-----", path + "/" + fileName);

						// path后如果没有"/",记得加"/"
						String cmdJson = CmdForm.generateJsonCmd(ownerId, path + "/" + fileName, CmdForm.CMD_DELETE_FOLDER);
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("CMD", cmdJson));
						HttpPostTask task = new HttpPostTask(context, ApiConstant.SMART_PAN_URL, params);
						task.setTaskListener(new OnTaskProcessListener() {
							@Override
							public void prepare() {
							}

							@Override
							public void completed(String result) {

								Log.i("-----", result);
								// String msg =
								// CmdForm.getOutputMessage(result);
								FileUtils.deleteFile(list.get(position).getPath());
								list.remove(position);
								notifyDataSetChanged();
								ToastUtils.show(context, "文件删除成功");
							}

						});
						task.execute();
					}
				}).show();
			}
		});

		// 下载按钮监听
		viewHolder.mySmartPanFileDown.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				final String fileName = list.get(position).getName();
				new AlertDialog.Builder(context).setTitle("提示").setMessage("确定下载该文件? : " + fileName).setNegativeButton("取消", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						String path = folderPath;
						Log.i("SmartPanListviewAdapter", "=+++++++++++++++++++++++++++++" + folderPath);
						list.get(position).setIsDown(Common.File.DOWNLOAD);
						notifyDataSetChanged();
						final String localPath = folderPath;
						String remotePath = localPath.replace(Common.rootFilePath.ROOT_FILE_PATH + ownerId, "");
						path = folderPath.replace(Common.rootFilePath.ROOT_FILE_PATH + ownerId, "");
						// path后如果没有"/",记得加"/"
						String cmdJson = CmdForm.generateJsonCmd(ownerId, remotePath + "/" + fileName, CmdForm.CMD_DOWNLOAD);
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("CMD", cmdJson));
						Log.i("-----", localPath + "/" + fileName);

						HttpPostTask task = new HttpPostTask(context, ApiConstant.SMART_PAN_URL, params, true);
						task.setTaskListener(new OnTaskProcessListener() {
							public void prepare() {
							}

							public void completed(String result) {
								if (!StringUtils.isEmptyOrStringNull(result)) {
									Log.i("---------", "下载成功:      " + result);
									byte[] resultByteArray = result.getBytes();
									FileUtils.saveByteArrayToFile(localPath + "/" + fileName, resultByteArray);
									Log.i("---------", "进度" + Long.parseLong(list.get(position).getSize()));

									list.get(position).setCondition(Common.File.HAVA);
									list.get(position).setIsDown(Common.File.NOT_DOWNLOAD);
									notifyDataSetChanged();

								} else {
									ToastUtils.show(context, "下载文件失败!");
								}
							}

						});
						task.execute();
					}
				}).show();

			}
		});

		return convertView;
	}

	public void getPostResult(String cmdJson) {
		// 做异步请求
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("CMD", cmdJson));
		HttpPostTask task = new HttpPostTask(context, ApiConstant.SMART_PAN_URL, params);
		task.setTaskListener(new OnTaskProcessListener() {
			public void prepare() {
			}

			public void completed(String result) {
				Log.i("SmartPanFragment", "同步返回数据: " + result);

				List<EntityBean> entityBeanList = new ArrayList<EntityBean>();
				if (CmdForm.fillEntityBeanList(entityBeanList, result)) {
					System.out.println("获取到的Size为: " + entityBeanList.size());
				} else {
					System.out.println("路径有问题");
				}
				// 本地数据与云盘对比
				list = SmartPanUtils.localWithSmartPanContrast(list, entityBeanList);
				// 云盘与本地对比
				list = SmartPanUtils.SmartPanContrastWithlocal(list, entityBeanList, context);
				setList(list);
				notifyDataSetChanged();
			}

		});
		task.execute();
	}

	private class ViewHolder {
		// 每个item的各种控件
		private CheckBox mySmartPanFileChoose;
		private ImageView mySmartPanFileType;
		private TextView mySmartPanFileName;
		private TextView mySmartPanFileTime;
		private TextView mySmartPanFileSize;
		private ImageButton mySmartPanFileDown, mySmartPanFileDelete;
		private ProgressBar mySmartPanDownBar;
	}

}
